package com.ndp.fb.walle.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.ndp.fb.constant.CommonConstants;
import com.ndp.fb.exception.CheckedException;
import com.ndp.fb.model.business.vo.ectemplate.EcDesignElementParam;
import com.ndp.fb.model.business.vo.ectemplate.EcElementFilterParam;
import com.ndp.fb.rdb.api.EcElementAttachRdbService;
import com.ndp.fb.rdb.model.Pager;
import com.ndp.fb.rdb.model.User;
import com.ndp.fb.rdb.model.ecelement.EcElementAttach;
import com.ndp.fb.util.StringUtil;
import com.ndp.fb.walle.business.EcElementService;
import com.ndp.fb.walle.model.vo.PageResult;
import com.ndp.fb.walle.util.ZipUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.InputStream;
import java.util.*;

/**
 * Created by Evan on 2016/7/7.
 */
@RestController
@RequestMapping("/ecelement")
public class EcElementController {
    Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    EcElementService ecElementService;

    /**
     * 模板元素查询
     */
    @RequestMapping("getByType")
    public List<EcElementAttach> getByType(@RequestBody EcElementAttach param, HttpServletRequest req) {
        User user = (User) req.getSession().getAttribute("user");
        return ecElementService.findByType(user.getOrgId(), param.getAttachElementType());
    }

    /**
     * 元素压缩包上传
     */
    @RequestMapping("upload")
    public Long upload(MultipartFile file, HttpServletRequest req) throws Exception {
        logger.info("EcTemplateController upload() begin.");
        User user = (User) req.getSession().getAttribute("user");
        String zipName = file.getOriginalFilename();
        //一、把前端传入的zip包  解压成文件夹形式
        InputStream input = file.getInputStream();
        String folder = req.getRealPath("/") + UUID.randomUUID().toString();
        try {
            ZipUtil.unzip(input, folder);
        } catch (Exception e) {
            logger.error("xxxxxxxxxxxx", e);
        }
        //二、对文件夹进行业务解析， 元素
        String templateId = req.getParameter("templateId");
        Long ecTemplateId;
        if(StringUtil.isEmpty(templateId)) {
            ecTemplateId = 0L;
        } else {
            ecTemplateId = Long.parseLong(templateId);
        }
        ecElementService.parse(user, ecTemplateId, folder + System.getProperty("file.separator") + ZipUtil.getFileNameNoEx(zipName));
        logger.info("EcTemplateController upload() end.");
        return 1L;
    }

    /**
     * 设计元素上传
     * @param req
     * @return
     * @throws Exception
     */
    @RequestMapping("uploadDesignEle")
    public EcElementAttach uploadDesignEle( MultipartFile uploadFile, HttpServletRequest req) throws Exception {
        logger.info("EcElementController uploadDesignEle() begin.");
        User user = (User) req.getSession().getAttribute("user");
        String filename = uploadFile.getOriginalFilename();
        String bgtype = req.getParameter("bgtype");
        if("1".equals(req.getParameter("type")) && StringUtil.isNotEmpty(bgtype) && !bgtype.equals(filename.split(CommonConstants.SYMBOL_UNDERLINE)[0])){
            throw new CheckedException("上传文件命名与模板主体背景类型不符！");
        }
        File elementAttachFile = new File(req.getRealPath("/") + UUID.randomUUID().toString());
        uploadFile.transferTo(elementAttachFile);
        EcElementAttach ecElementAttach = ecElementService.insert(user, filename, elementAttachFile);
        logger.info("EcElementController uploadDesignEle() end.");
        return ecElementAttach;
    }

    @RequestMapping("uploadDesignEleAll")
    public Long uploadDesignEleAll( MultipartFile uploadFile, HttpServletRequest req) throws Exception {
        logger.info("EcElementController uploadDesignEleAll() begin.");
        User user = (User) req.getSession().getAttribute("user");
        String filename = uploadFile.getOriginalFilename();
        File elementAttachFile = new File(req.getRealPath("/") + UUID.randomUUID().toString());
        uploadFile.transferTo(elementAttachFile);
        ecElementService.insert(user, filename, elementAttachFile);
        logger.info("EcElementController uploadDesignEleAll() end.");
        return 1L;
    }



    /**
     * 获取所有设计元素
     */
    @RequestMapping("getAllDesignEle")
    public List<EcElementAttach> getAllDesignEle(@RequestBody EcDesignElementParam param, HttpServletRequest req) throws Exception {
        logger.info("EcElementController getAllDesignEle() begin.");
        User user = (User) req.getSession().getAttribute("user");
        List<EcElementAttach> res = ecElementService.getAllAttach(user.getOrgId());
        logger.info("EcElementController getAllDesignEle() end.");
        return res;
    }

    @RequestMapping("getAllDesignElePage")
    public Map getAllDesignElePage(@RequestBody EcDesignElementParam param, HttpServletRequest req) throws Exception {
        logger.info("EcElementController getAllDesignEle() begin.");
        User user = (User) req.getSession().getAttribute("user");
        Integer sizeNo = param.getPSize() == null || param.getPSize() < 1 ? CommonConstants.DEFAULT_PAGE_SIZE_5 : param.getPSize();
        Integer firstResult = param.getCPage() == null  || param.getCPage() < 1? 0 : (param.getCPage() - 1) * sizeNo;
        Pager<EcElementAttach> results = ecElementService.getAllDesignEle(user.getOrgId(), param.getType(), firstResult, sizeNo);
        Long tSize = results.getTotalSize() == null ? 0 : results.getTotalSize();
        float nrOfPages = (float) tSize / sizeNo;
        int tPage = (int) ((nrOfPages > (int) nrOfPages || nrOfPages == 0.0) ? nrOfPages + 1 : nrOfPages);
        PageResult pageResult = new PageResult(tPage, param.getCPage(), sizeNo, tSize);

        // 封装响应结果
        Map data = new HashMap<>();
        data.put("attaches", results.getResultList());
        data.put("paginator", pageResult);
        logger.info("EcElementController getAllDesignEle() end.");
        return data;
    }

}
